package com.wetest.uia2.stub;

import android.app.UiAutomation;
import android.os.Build;
import android.util.SparseArray;
import android.util.Xml;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.accessibility.AccessibilityWindowInfo;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TableLayout;

import androidx.test.internal.runner.listener.InstrumentationResultPrinter;
import androidx.test.uiautomator.UiAutomationHelper;
import androidx.test.uiautomator.UiDevice;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.uiautomator.AutoTaskService;
import com.wetest.uia2.Ln;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.xmlpull.v1.XmlSerializer;

import uiautomator.InstrumentShellWrapper;

/* loaded from: classes9.dex */
class AccessibilityNodeInfoDumper {
    private static final String TAG = AccessibilityNodeInfoDumper.class.getSimpleName();
    private static final String[] NAF_EXCLUDED_CLASSES = {GridView.class.getName(), GridLayout.class.getName(), ListView.class.getName(), TableLayout.class.getName()};

    private AccessibilityNodeInfoDumper() {
    }

    public static void dumpWindowHierarchy(/*UiDevice device,*/ OutputStream out, int maxDepth) throws IOException {
//        Ln.i("dumpWindowHierarchy->" + device.getCurrentPackageName());
        XmlSerializer serializer = Xml.newSerializer();
        serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
        serializer.setOutput(out, "UTF-8");
        serializer.startDocument("UTF-8", true);
        serializer.startTag(JsonProperty.USE_DEFAULT_NAME, "hierarchy");
//        serializer.attribute(JsonProperty.USE_DEFAULT_NAME, "rotation", Integer.toString(device.getDisplayRotation()));
        for (AccessibilityNodeInfo root : getWindowRoots(/*device*/)) {
            dumpNodeRec(root, serializer, 0, 1080/*device.getDisplayWidth()*/, 1920/*device.getDisplayHeight()*/, maxDepth);
        }
        serializer.endTag(JsonProperty.USE_DEFAULT_NAME, "hierarchy");
        serializer.endDocument();
    }

    static AccessibilityNodeInfo[] getWindowRoots(/*UiDevice device*/) {
//        device.waitForIdle();
        Set<AccessibilityNodeInfo> roots = new HashSet<>();
//        UiAutomation uiAutomation = UiAutomationHelper.getUiAutomation();//UiDevice.getInstance(InstrumentShellWrapper.getInstance()).getUiAutomation();
        AccessibilityNodeInfo activeRoot = AutoTaskService.accessibilityService.getRootInActiveWindow();//uiAutomation.getRootInActiveWindow();
        if (activeRoot != null) {
            roots.add(activeRoot);
            Ln.i("activeRoot->" + activeRoot);
        } else {
            Ln.i("Active window root not found.");
        }
        for (AccessibilityWindowInfo window : getWindows(/*uiAutomation*/)) {
            AccessibilityNodeInfo root = window.getRoot();
            if (root == null) {
                android.util.Log.w(TAG, "Skipping null root node for window: " + window);
            } else {
                roots.add(root);
            }
        }
        return (AccessibilityNodeInfo[]) roots.toArray(new AccessibilityNodeInfo[0]);
    }

    private static List<AccessibilityWindowInfo> getWindows(/*UiAutomation uiAutomation*/) {
        try {
            if (Build.VERSION.SDK_INT >= 30) {
                List<AccessibilityWindowInfo> windowList = new ArrayList<>();
                SparseArray<List<AccessibilityWindowInfo>> allWindows = AutoTaskService.accessibilityService.getWindowsOnAllDisplays();//uiAutomation.getWindowsOnAllDisplays();
                for (int index = 0; index < allWindows.size(); index++) {
                    windowList.addAll(allWindows.valueAt(index));
                }
                return windowList;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return AutoTaskService.accessibilityService.getWindows();//uiAutomation.getWindows();
    }

    private static void dumpNodeRec(AccessibilityNodeInfo node, XmlSerializer serializer, int index, int width, int height, int maxDepth) throws IOException {
        serializer.startTag(JsonProperty.USE_DEFAULT_NAME, "node");
        if (!nafExcludedClass(node) && !nafCheck(node)) {
            serializer.attribute(JsonProperty.USE_DEFAULT_NAME, "NAF", Boolean.toString(true));
        }
        serializer.attribute(JsonProperty.USE_DEFAULT_NAME, "index", Integer.toString(index));
        try {
            serializer.attribute(JsonProperty.USE_DEFAULT_NAME, "text", safeCharSeqToString(node.getText()));
            serializer.attribute(JsonProperty.USE_DEFAULT_NAME, "resource-id", safeCharSeqToString(node.getViewIdResourceName()));
            serializer.attribute(JsonProperty.USE_DEFAULT_NAME, InstrumentationResultPrinter.REPORT_KEY_NAME_CLASS, safeCharSeqToString(node.getClassName()));
            serializer.attribute(JsonProperty.USE_DEFAULT_NAME, "package", safeCharSeqToString(node.getPackageName()));
            serializer.attribute(JsonProperty.USE_DEFAULT_NAME, "content-desc", safeCharSeqToString(node.getContentDescription()));
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        serializer.attribute(JsonProperty.USE_DEFAULT_NAME, "checkable", Boolean.toString(node.isCheckable()));
        serializer.attribute(JsonProperty.USE_DEFAULT_NAME, "checked", Boolean.toString(node.isChecked()));
        serializer.attribute(JsonProperty.USE_DEFAULT_NAME, "clickable", Boolean.toString(node.isClickable()));
        serializer.attribute(JsonProperty.USE_DEFAULT_NAME, "enabled", Boolean.toString(node.isEnabled()));
        serializer.attribute(JsonProperty.USE_DEFAULT_NAME, "focusable", Boolean.toString(node.isFocusable()));
        serializer.attribute(JsonProperty.USE_DEFAULT_NAME, "focused", Boolean.toString(node.isFocused()));
        serializer.attribute(JsonProperty.USE_DEFAULT_NAME, "scrollable", Boolean.toString(node.isScrollable()));
        serializer.attribute(JsonProperty.USE_DEFAULT_NAME, "long-clickable", Boolean.toString(node.isLongClickable()));
        serializer.attribute(JsonProperty.USE_DEFAULT_NAME, "password", Boolean.toString(node.isPassword()));
        serializer.attribute(JsonProperty.USE_DEFAULT_NAME, "selected", Boolean.toString(node.isSelected()));
        serializer.attribute(JsonProperty.USE_DEFAULT_NAME, "visible-to-user", Boolean.toString(node.isVisibleToUser()));
        serializer.attribute(JsonProperty.USE_DEFAULT_NAME, "bounds", AccessibilityNodeInfoHelper.getVisibleBoundsInScreen(node, width, height, false).toShortString());
        if (Build.VERSION.SDK_INT >= 24) {
            serializer.attribute(JsonProperty.USE_DEFAULT_NAME, "drawing-order", Integer.toString(Api24Impl.getDrawingOrder(node)));
        }
        if (Build.VERSION.SDK_INT >= 26) {
            serializer.attribute(JsonProperty.USE_DEFAULT_NAME, "hint", safeCharSeqToString(Api26Impl.getHintText(node)));
        }
        if (Build.VERSION.SDK_INT >= 30) {
            serializer.attribute(JsonProperty.USE_DEFAULT_NAME, "display-id", Integer.toString(Api30Impl.getDisplayId(node)));
        }
        if (maxDepth > 0) {
            int count = node.getChildCount();
            for (int i = 0; i < count; i++) {
                AccessibilityNodeInfo child = node.getChild(i);
                if (child != null) {
                    if (child.isVisibleToUser()) {
                        dumpNodeRec(child, serializer, i, width, height, maxDepth - 1);
                        child.recycle();
                    } else {
                        android.util.Log.i(TAG, String.format("Skipping invisible child: %s", child));
                    }
                } else {
                    android.util.Log.i(TAG, String.format("Null child %d/%d, parent: %s", Integer.valueOf(i), Integer.valueOf(count), node));
                }
            }
        }
        serializer.endTag(JsonProperty.USE_DEFAULT_NAME, "node");
    }

    private static boolean nafExcludedClass(AccessibilityNodeInfo node) {
        String className = safeCharSeqToString(node.getClassName());
        for (String excludedClassName : NAF_EXCLUDED_CLASSES) {
            if (className.endsWith(excludedClassName)) {
                return true;
            }
        }
        return false;
    }

    private static boolean nafCheck(AccessibilityNodeInfo node) {
        boolean isNaf = node.isClickable() && node.isEnabled() && safeCharSeqToString(node.getContentDescription()).isEmpty() && safeCharSeqToString(node.getText()).isEmpty();
        if (isNaf) {
            return childNafCheck(node);
        }
        return true;
    }

    private static boolean childNafCheck(AccessibilityNodeInfo node) {
        int childCount = node.getChildCount();
        for (int x = 0; x < childCount; x++) {
            AccessibilityNodeInfo childNode = node.getChild(x);
            if (childNode != null && (!safeCharSeqToString(childNode.getContentDescription()).isEmpty() || !safeCharSeqToString(childNode.getText()).isEmpty() || childNafCheck(childNode))) {
                return true;
            }
        }
        return false;
    }

    private static String safeCharSeqToString(CharSequence cs) {
        return cs == null ? JsonProperty.USE_DEFAULT_NAME : stripInvalidXMLChars(cs);
    }

    private static String stripInvalidXMLChars(CharSequence cs) {
        StringBuilder ret = new StringBuilder();
        for (int i = 0; i < cs.length(); i++) {
            char ch = cs.charAt(i);
            if ((ch >= 0 && ch <= '\b') || ((ch >= 11 && ch <= '\f') || ((ch >= 14 && ch <= 31) || ((ch >= 127 && ch <= 132) || ((ch >= 134 && ch <= 159) || ((ch >= 55296 && ch <= 57343) || ((ch >= 64976 && ch <= 64991) || (ch >= 65534 && ch <= 65535)))))))) {
                ret.append(".");
            } else {
                ret.append(ch);
            }
        }
        return ret.toString();
    }

    static class Api24Impl {
        private Api24Impl() {
        }

        static int getDrawingOrder(AccessibilityNodeInfo accessibilityNodeInfo) {
            return accessibilityNodeInfo.getDrawingOrder();
        }
    }

    static class Api26Impl {
        private Api26Impl() {
        }

        static String getHintText(AccessibilityNodeInfo accessibilityNodeInfo) {
            CharSequence chars = accessibilityNodeInfo.getHintText();
            if (chars != null) {
                return chars.toString();
            }
            return null;
        }
    }

    static class Api30Impl {
        private Api30Impl() {
        }

        static int getDisplayId(AccessibilityNodeInfo accessibilityNodeInfo) {
            AccessibilityWindowInfo accessibilityWindowInfo = accessibilityNodeInfo.getWindow();
            if (accessibilityWindowInfo == null) {
                return 0;
            }
            return accessibilityWindowInfo.getDisplayId();
        }
    }
}